/**
 * 
 */
package com.edu.lawdoc.api.utils;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author xiao.hu
 *
 */
public class FileKit {

	/**
	 * 从InputStream中获得内容，此方法性能比较好
	 *
	 * @return
	 * @throws IOException
	 */
	public static String getContent(String filePath) throws IOException {
		try (InputStream in = new FileInputStream(filePath)) {
			ByteArrayOutputStream result = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int length;
			while ((length = in.read(buffer)) != -1) {
				result.write(buffer, 0, length);
			}
			return result.toString("UTF-8");
		}
	}
	
	/**
	 * 从InputStream中获得字节内容，此方法性能比较好
	 * @param filePath
	 * @return
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	public static byte[] getBytes(String filePath) throws FileNotFoundException, IOException {
		try (InputStream in = new FileInputStream(filePath)) {
			ByteArrayOutputStream result = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int length;
			while ((length = in.read(buffer)) != -1) {
				result.write(buffer, 0, length);
			}
			return result.toByteArray();
		}
	}


	public static String getAbsolutePath(String fileName) {
		return Thread.currentThread().getContextClassLoader().getResource(fileName).getFile();
	}
}
